package com.karaoke.android.home

import android.content.Context
import android.content.Intent
import android.hardware.display.DisplayManager
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import com.apkfuns.logutils.LogUtils
import com.dewarder.akommons.displayManager
import com.github.javiersantos.materialstyleddialogs.MaterialStyledDialog
import com.github.javiersantos.materialstyleddialogs.enums.Style
import com.karaoke.android.data.NetworkTools
import com.karaoke.android.data.domain.PlayList
import com.karaoke.android.data.krealmextensions.saveAll
import com.karaoke.android.data.onIO
import com.karaoke.android.data.onUI
import com.karaoke.android.data.service.MediaListService
import com.karaoke.android.data.utils.hideSystemBar
import com.karaoke.android.home.databinding.ActivityHomeBinding
import com.karaoke.android.home.fragment.MediaListFragment
import com.karaoke.android.home.fragment.QuickActionDialogFragment.ALIGN_ANCHOR_VIEW_BOTTOM
import com.karaoke.android.home.fragment.QuickActionDialogFragment.ALIGN_ANCHOR_VIEW_RIGHT
import com.karaoke.android.home.fragment.VideoFragment
import com.karaoke.android.home.vm.MainViewModel
import com.karaoke.android.home.widget.AuraPopup
import com.karaoke.android.home.widget.VolumePopup
import com.karaoke.android.library.BaseApp
import com.karaoke.android.library.mvvm.MvvmTabActivity
import com.karaoke.android.library.utils.Utils
import com.karaoke.android.player.VideoManager
import com.labo.kaji.relativepopupwindow.RelativePopupWindow
import io.realm.RealmChangeListener
import org.simple.eventbus.EventBus

class HomeActivity : MvvmTabActivity<MainViewModel>()
{

    override val viewModel: MainViewModel by lazy { MainViewModel() }

    private val mBinding by lazy { ActivityHomeBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        updatePresentation()
        EventBus.getDefault().register(this)
        mBinding.viewModel = viewModel
        displayManager.registerDisplayListener(mDisplayListener, null)
        setContentView(mBinding.root)
        tabHost.addTab(tabHost.newTabSpec("a").setIndicator("Kge").setContent(Intent().setClassName(this, "com.karaoke.android.kege.KegeActivity")))
        NetworkTools.dictionaryService.dictionary().onIO().onUI({ it.saveAll() }, {})
    }


    private val mediaListChangeListener = RealmChangeListener<PlayList> {
        EventBus.getDefault().post(it)
    }


    private val mDisplayListener = object : DisplayManager.DisplayListener
    {
        override fun onDisplayChanged(displayId: Int)
        {
            updatePresentation()
            LogUtils.e("onDisplayChanged $displayId")
        }

        override fun onDisplayAdded(displayId: Int)
        {
            updatePresentation()
            LogUtils.e("onDisplayAdded $displayId")
        }

        override fun onDisplayRemoved(displayId: Int)
        {
            updatePresentation()
            LogUtils.e("onDisplayRemoved $displayId")
        }

    }

    override fun onDestroy()
    {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    var mPresentation: VideoFragment? = null

    private fun updatePresentation()
    {
        if (application is BaseApp)
        {
            mPresentation = (application as BaseApp).mPresentation as VideoFragment?
            val presentationDisplay = if (displayManager.displays.size > 1) displayManager.displays[1] else null

            mPresentation?.let {
                if (it.display.displayId != presentationDisplay?.displayId)
                {
                    mPresentation?.dismiss()
                    mPresentation = null
                }
                else
                {
                    this.mBinding.videoModel = mPresentation?.viewModel
                    this.mBinding.executePendingBindings()
                }
            }
            if (mPresentation == null && presentationDisplay != null)
            {
                LogUtils.w("Showing presentation on display: " + presentationDisplay)
                mPresentation = VideoFragment(applicationContext, presentationDisplay)
                (application as BaseApp).mPresentation = mPresentation
                this.mBinding.videoModel = mPresentation?.viewModel
                this.mBinding.executePendingBindings()
                try
                {
                    mPresentation?.show()
                }
                catch (ex: WindowManager.InvalidDisplayException)
                {
                    LogUtils.w("Couldn't show presentation!  Display was removed in " + "the meantime.", ex)
                    mPresentation = null
                }
            }
        }
    }


    fun onToggleService(view: View)
    {
        VideoManager.onToggleService()
    }

    fun onToggleYuanBanChang(view: View)
    {
        VideoManager.toggleAccompany()
    }

    fun onMute(view: View)
    {
        VideoManager.toggleMute()
    }

    fun onPause(view: View)
    {
        VideoManager.togglePause()
    }

    fun onCut(view: View)
    {
        if (Utils.isFastClick()) return
        MediaListService.nextPlay()
    }

    fun onReplay(view: View)
    {
        VideoManager.onReplay()
    }

    private val volumePopup by lazy {
        VolumePopup(this)
    }



    fun showVolumeBar(v: View)
    {
        volumePopup.showOnAnchor(v, RelativePopupWindow.VerticalPosition.CENTER, RelativePopupWindow.HorizontalPosition.CENTER)
    }

    private val auraDialog by lazy {
        AuraPopup(this)
    }

    fun showAura(view: View)
    {
        auraDialog.showOnAnchor(view, RelativePopupWindow.VerticalPosition.CENTER, RelativePopupWindow.HorizontalPosition.CENTER)
    }

    fun showPlayListDialog(view: View)
    {
        MediaListFragment()
                .setAnchorView(view)
                .setAligmentFlags(ALIGN_ANCHOR_VIEW_RIGHT or ALIGN_ANCHOR_VIEW_BOTTOM)
                .show(fragmentManager, "playlist")
    }


    fun showPasswordDialog(view: View): Boolean
    {
        val inflater = view.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        val customView = inflater.inflate(R.layout.setting_input_pwd, null)

        val edit = customView.findViewById(R.id.editText) as EditText
        val dialog = MaterialStyledDialog.Builder(view.context)
                .setTitle("系统设置")
                .setDescription("进入系统设置，请输入系统密码")
                .setCustomView(customView)
                .setStyle(Style.HEADER_WITH_TITLE)
                .setPositiveText("确定")
                .onPositive { _, _ ->
                    val pwd = edit.text.toString()
                    if (pwd == "0909")
                    {
                        Settings.System.putInt(view.context.contentResolver, "systembar_hide", 0)
                        val i = Intent("com.tchip.changeBarHideStatus")
                        view.context.sendBroadcast(i)
                        val intent = Intent(Settings.ACTION_SETTINGS)
                        view.context.startActivity(intent)
                    }
                }
                .show()

        return true
    }

    override fun onResume()
    {
        super.onResume()
        hideSystemBar(true)

    }

    fun onSearch(view: View)
    {
        EventBus.getDefault().post("onSearch", "onSearch")
    }

    override fun onBackPressed()
    {

    }
}

